package com.cennavi.mineplay.mineplay_data.model.DBConnectionImp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.cennavi.mineplay.mineplay_data.model.DBConnectionInfo;
import com.cennavi.mineplay.mineplay_data.model.DbNameInfo;
import com.cennavi.mineplay.mineplay_data.model.db.inter.DBConnection;

public class PostgresConnectionImpl implements DBConnection{
	private DbNameInfo dbNameInfo;
	private DBConnectionInfo dbConnectionInfo;
	
	public PostgresConnectionImpl(DbNameInfo dbNameInfo, DBConnectionInfo dbConnectionInfo){
		this.dbNameInfo = dbNameInfo;
		this.dbConnectionInfo = dbConnectionInfo;
	}
	
	public Connection[] getConnnection(){
		List<String> dbNames = dbNameInfo.getDBName();
		String url = "";
		Connection[] connections = null;
		if(dbNames.size() != 0){
			connections = new Connection[dbNames.size()];
			for(String s : dbNames){
				int index = 0;
				String Driver = dbConnectionInfo.getDriverClass();
				//jdbc:postgresql://192.168.100.120:5432/postgres
				url = "jdbc:postgresql://" + dbConnectionInfo.getJdbc() + "/" + s;
				Connection con;
				try{
					Class.forName(Driver);
					con = DriverManager.getConnection(url,dbConnectionInfo.getUsername(),dbConnectionInfo.getPassword());
					if(con != null){
						connections[index] = con;
					}
				}catch(ClassNotFoundException e){
					e.printStackTrace();
				}catch(SQLException e){
					e.printStackTrace();
				}finally{
				}
				index++;
			}
		}
		return connections;
	}
	
	public String getSql(){
		int updateStyle = dbConnectionInfo.getUpdateStyle();
		
		int frequency = -dbConnectionInfo.getFrequency();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.SECOND, frequency);
		String timeSection_pre = sdf.format(calendar.getTime()).toString();
		String timeSection_fol = sdf.format(new Date()).toString();
		String timeName = dbConnectionInfo.getTimeName();
		String whereSql = "";
		if(updateStyle == 1){
			whereSql = "1=1";
		}else if(updateStyle == 0){
			whereSql = timeName + " BETWEEN "
								+ "'" + timeSection_pre + "'"
								+ " AND "
								+ "'" + timeSection_fol + "'";
		}
		return whereSql;
	}
}
